import request from "@/utils/request";
import axios from 'axios'

const api_name = "/tiku";

export default {
  getTiku() {
    return request({
      url: `${api_name}/tiku/list`,
      method: 'get'
    });
  },
  insert(tiku) {
    console.log(tiku)
    return request({
      url: `${api_name}/tiku/insert`,
      method: 'post',
      data: tiku
    });
  },
  // console.log(`${api_name}/tiku/random/${e}`)
  // return request({
  //   url: `${api_name}/tiku/random/${e}`,
  //   method: 'get',
  // });
  random(e) {
    return new Promise((resolve, reject) => {
      axios.get(`http://localhost:8080/tiku/tiku/random/${e}`, { responseType: 'blob' })
        .then(response => {
          const blob = new Blob([response.data], { type: 'text/plain' })
          const fileName = `${e}.txt`
          if (window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveBlob(blob, fileName)
          } else {
            const link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = fileName
            link.click()
            window.URL.revokeObjectURL(link.href)
          }
          resolve('已下载题目')
        })
        .catch(error => {
          reject(error)
        });
    })
  },
  answer(e){
    return new Promise((resolve, reject) => {
      axios.get(`http://localhost:8080/tiku/tiku/answer/${e}`, { responseType: 'blob' })
        .then(response => {
          const blob = new Blob([response.data], { type: 'text/plain' })
          const fileName = `${e}-答案.txt`
          if (window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveBlob(blob, fileName)
          } else {
            const link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = fileName
            link.click()
            window.URL.revokeObjectURL(link.href)
          }
          resolve('已下载答案')
        })
        .catch(error => {
          reject(error)
        });
    })
  }
};